import {
  ExceptionFilter,
  Catch,
  HttpException,
  ArgumentsHost
} from '@nestjs/common'
import { Request, Response } from 'express'
import { Logger } from 'src/utils/log4js'
import { Log } from 'src/modules/log/entities/log.entity' // 导入 Log 实体
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { DateUtil } from 'src/utils'
import { Staff } from 'src/modules/staff/entities/staff.entity'

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(
    @InjectRepository(Log) private readonly log: Repository<Log>,
    @InjectRepository(Staff) private readonly staff: Repository<Staff>
  ) {}
  async catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const request = ctx.getRequest<Request>()
    const response = ctx.getResponse<Response>()
    const status = exception.getStatus()
    const logFormat = ` <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    Request original url: ${request.originalUrl}
    Method: ${request.method}
    IP: ${request.ip}
    Status code: ${status}
    Response: ${
      JSON.parse(JSON.stringify(exception)).response.message
    }\n  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<`

    // 保存日志信息到数据库
    const log = new Log()
    const id = request.user ? (request.user as any).id : null
    id && (log.staff = await this.staff.findOne({ where: { id } }))
    log.url = request.originalUrl
    log.method = request.method
    log.ip = request.ip
    log.code = status
    log.date = new DateUtil(new Date(), 'yyyy-MM-dd hh:mm:ss').format()
    await this.log.save(log)

    Logger.info(logFormat)
    response.status(status).json({
      code: status,
      success: false,
      error: JSON.parse(JSON.stringify(exception)).response.message,
      timestamp: new Date().toISOString(),
      msg: `${status >= 500 ? 'Service Error' : 'Client Error'}`
    })
  }
}
